package vn.edu.ptithcm.pim.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.common.bean.PaginationObject;
import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.Paginations;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Application;
import vn.edu.ptithcm.pim.dom.Customer;
import vn.edu.ptithcm.pim.query.CustomerQuery;
import vn.edu.ptithcm.pim.service.CustomerService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class CustomerController extends SimpleFormController {
	private UserService userService;
	private CustomerService customerService;
	Log log = LogFactory.getLog(CustomerController.class);
	private int ITEMS_PER_PAGE = 5;
	private List<Integer> itemsPerPage = new ArrayList<Integer>();

	public CustomerController() {
		super();
		setSessionForm(true);
		setCommandClass(CustomerQuery.class);
		setCommandName("customerQuery");
		setFormView(UrlConstants.CUSTOMERS_URL);
		setSuccessView(UrlConstants.CUSTOMERS_URL);

		this.itemsPerPage.add(5);
		this.itemsPerPage.add(10);
		this.itemsPerPage.add(20);
		this.itemsPerPage.add(30);
		this.itemsPerPage.add(50);
		this.itemsPerPage.add(75);
		this.itemsPerPage.add(100);

	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		CustomerQuery customerQuery = new CustomerQuery();
		return customerQuery;
	}

	private void pagingCustomer(HttpServletRequest request,
			CustomerQuery customerQuery) {
		try {
			PaginationObject paging = null;
			List<Customer> customers = new ArrayList<Customer>();
			int total = 0;

			int currentPage = ParamUtil.getInteger(request,
					Paginations.CURRENT_PAGE_NUM, 1);
			int pageSize = ParamUtil.getInteger(request, Paginations.PAGE_SIZE,
					ITEMS_PER_PAGE);

			total = customerService.countByQuery(customerQuery);
			paging = new PaginationObject("customerPaging", total);
			paging.setItemsPerPage(itemsPerPage);
			paging.paging(currentPage, pageSize);

			int max = paging.getEndIndex() - paging.getStartIndex();
			customers.addAll(customerService.findByQuery(customerQuery, max,
					paging.getStartIndex()));

			request.setAttribute("customers", customers);
			request.setAttribute("paging", paging);
			request.setAttribute("total", total);

			log.info("results : " + customers.size() + " customers");
			log.info("total : " + total);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		CustomerQuery query = (CustomerQuery) command;
		String cmd = ParamUtil.getString(request, "cmd", "");

		if ("searchCustomers".equals(cmd)) {
			pagingCustomer(request, query);
		} else if ("deleteCustomers".equals(cmd)) {
			if (query.getCustomerIds().size() > 0) {
				for (int i = 0; i < query.getCustomerIds().size(); ++i) {
					customerService.deleteById(new Long(query.getCustomerIds()
							.get(i)));
				}
			}
			pagingCustomer(request, query);
		}

		return showForm(request, response, errors);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		if (userService.isSignedIn(request)) {
			Map<String, Object> bean = new HashMap<String, Object>();
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			bean.put("isAdmin", userService.isAdmin(loginName));

			List<Customer> customers = new ArrayList<Customer>();

			if (request.getAttribute("customers") == null) {
				log.info("customers == null");

				String searchKey = ParamUtil.getString(request, "key", "");
				CustomerQuery query = new CustomerQuery();
				query.setSearchKey(searchKey);

				pagingCustomer(request, query);
			}

			customers = (List<Customer>) ParamUtil.getObject(request,
					"customers", null);

			bean.put("pagingUrl", request.getRequestURL().toString());

			bean.put("paging", ParamUtil.getObject(request, "paging", null));

			bean.put("total", ParamUtil.getObject(request, "total", null));

			bean.put("itemsPerPage", ITEMS_PER_PAGE);

			bean.put("customers", customers);
			bean.put("countList", customers.size());

			List<Application> applications = userService
					.getApplications(loginName);

			String selectedPage = "";
			String viewURL = request.getRequestURI();

			for (Application p : applications) {
				String friendlyUrl = p.getFriendlyurl();
				if (viewURL.indexOf(friendlyUrl) != -1) {
					selectedPage = friendlyUrl;
					break;
				}
			}

			bean.put("selectedPage", selectedPage);
			bean.put("applications", applications);
			String currentURL = request.getRequestURL().toString();
			int indexCurrentPage = currentURL.indexOf("?currentPage");

			if (indexCurrentPage != -1) {
				currentURL = currentURL.substring(0, indexCurrentPage);
			}
			bean.put("currentURL", currentURL);

			String pageURL = currentURL;
			int indexPage = pageURL.indexOf("?");
			if (indexPage != -1) {
				pageURL = pageURL.substring(0, indexPage);
			}
			bean.put("pageURL", pageURL);

			request.setAttribute("bean", bean);
		} else {
			String redirectLink = UrlConstants.CUSTOMERS_URL + UrlConstants.HTM;
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return super.showForm(request, response, errors);
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
